package com.wisdom.benefit.jufa.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.ansen.http.net.HTTPCaller;
import com.wisdom.benefit.jufa.product.AccountFragment;
import com.wisdom.benefit.jufa.my.MineFragment;
import com.wisdom.benefit.jufa.news.OrderFragment;
import com.wisdom.benefit.jufa.R;
import com.wisdom.benefit.jufa.base.BaseActivity;
import com.wisdom.benefit.jufa.net.RetrofitService;
import com.wisdom.benefit.jufa.utils.CommonUtils;
import com.wisdom.benefit.jufa.widget.NoScrollViewPager;
import com.wisdom.benefit.jufa.widget.PointRadioButton;

import java.io.File;

import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.ycbjie.ycstatusbarlib.bar.YCAppBar;
import io.github.lizhangqu.coreprogress.ProgressUIListener;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends BaseActivity {
    @SuppressLint("StaticFieldLeak")
    public static MainActivity mainActivity;
    private static final String KEY_CHECKED_POSITION = "mCheckedPosition";
    private String url;
    private String newVersion;
    private String mandatoryUpdate;
    private ProgressDialog progressDialog;
    @BindView(R.id.fragment_container)
    NoScrollViewPager fragmentContainer;
    @BindView(R.id.id_main_bottom_bar_tab_main)
    PointRadioButton idMainBottomBarTabMain;
    @BindView(R.id.id_main_bottom_bar)
    RadioGroup idMainBottomBar;
    private LocationReceiver locationReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainActivity = this;
        setStatusBar();
        mTopBarEndText.setCompoundDrawablesRelativeWithIntrinsicBounds(R.drawable.ic_search2, 0, 0, 0);
        mTopBarEndContainer.setVisibility(View.VISIBLE);
        mTopBarDivider.setVisibility(View.VISIBLE);
        idMainBottomBarTabMain.performClick();
        locationReceiver = new LocationReceiver();


        IntentFilter filter = new IntentFilter();
        filter.addAction("location.reportsucc");
        registerReceiver(locationReceiver, filter);
        checkPermission();
        appUpdate();

    }

    public void checkPermission() {
        boolean isGranted = true;
        if (android.os.Build.VERSION.SDK_INT >= 23) {
            if (MainActivity.this.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                //如果没有写sd卡权限
                isGranted = false;
            }
            if (MainActivity.this.checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                isGranted = false;
            }
            Log.i("cbs", "isGranted == " + isGranted);
            if (!isGranted) {
                (MainActivity.this).requestPermissions(
                        new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        102);
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(locationReceiver);
        mainActivity = null;
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initViews() {
        mUnbinder = ButterKnife.bind(this);

        mTopBarStartContainer.setVisibility(View.GONE);
        fragmentContainer.setNoScroll(true);
        fragmentContainer.setAdapter(mPagerAdapter);
        fragmentContainer.setOffscreenPageLimit(3);

        idMainBottomBar.setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == R.id.id_main_bottom_bar_tab_main) {
                setTitleText(R.string.main_bottom_bar_tab_main);
                mTopBarContainer.setVisibility(View.GONE);
                mTopBarDivider.setVisibility(View.GONE);
                fragmentContainer.setCurrentItem(0, false);
                //设置状态栏为蓝色
                YCAppBar.setStatusBarColor(MainActivity.this,
                        ContextCompat.getColor(MainActivity.this,
                                R.color.blue));
                //状态栏亮色模式，设置状态栏黑色文字、图标
//                StatusBarUtils.StatusBarLightMode(MainActivity.this);
            } else if (checkedId == R.id.id_main_bottom_bar_tab_product) {
                setTitleText(R.string.main_bottom_bar_tab_product);
                mTopBarContainer.setVisibility(View.GONE);
                mTopBarDivider.setVisibility(View.GONE);
                fragmentContainer.setCurrentItem(1, false);
                YCAppBar.setStatusBarColor(MainActivity.this,
                        ContextCompat.getColor(MainActivity.this,
                                R.color.blue));
            } else if (checkedId == R.id.id_main_bottom_bar_tab_news) {
                setTitleText(R.string.main_bottom_bar_tab_news);
                mTopBarContainer.setVisibility(View.GONE);
                mTopBarDivider.setVisibility(View.GONE);
                fragmentContainer.setCurrentItem(2, false);
                YCAppBar.setStatusBarColor(MainActivity.this,
                        ContextCompat.getColor(MainActivity.this,
                                R.color.blue));
            } else if (checkedId == R.id.id_main_bottom_bar_tab_my) {
                setTitleText(R.string.main_bottom_bar_tab_my);
                mTopBarContainer.setVisibility(View.GONE);
                mTopBarDivider.setVisibility(View.GONE);
                fragmentContainer.setCurrentItem(3, false);
                YCAppBar.setStatusBarColor(MainActivity.this,
                        ContextCompat.getColor(MainActivity.this,
                                R.color.blue));
            }
        });
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.main_bottom_bar_tab_main;
    }

    @OnClick({R.id.id_main_bottom_bar_tab_main, R.id.id_main_bottom_bar_tab_product,
            R.id.id_main_bottom_bar_tab_news, R.id.id_main_bottom_bar_tab_my})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_main_bottom_bar_tab_main:
            case R.id.id_main_bottom_bar_tab_product:
            case R.id.id_main_bottom_bar_tab_news:
            case R.id.id_main_bottom_bar_tab_my:
                break;
        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v.getId() == R.id.top_bar_end_container) {
        }
    }

    private boolean mIsFirstPressed = true;

    @Override
    public void onBackPressed() {
        if (mIsFirstPressed) {
            mIsFirstPressed = false;
            showToast(R.string.press_again_to_exit_app);
            mTopBarContainer.postDelayed(() -> mIsFirstPressed = true, 2000L);
        } else {// 两秒内点击两次
            finish();
            System.exit(0);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        int position = intent.getIntExtra(KEY_CHECKED_POSITION, -1);
        Log.e("onNewIntent", "" + position);
        if (position >= 0 && position <= 3) {
            idMainBottomBar.getChildAt(position).performClick();
        }
    }

    public static void toTabPage(Context context, int position, Bundle bundle) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra(MainActivity.KEY_CHECKED_POSITION, position);
        intent.putExtras(bundle == null ? new Bundle() : bundle);
        context.startActivity(intent);
    }

    private HomeFragment getMainFragment() {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(
                makeFragmentName(fragmentContainer.getId(), HomeFragment.TAG.hashCode()));
        if (fragment == null) {
            fragment = HomeFragment.newInstance();
        }
        return (HomeFragment) fragment;
    }

    private OrderFragment getAccountFragment() {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(
                makeFragmentName(fragmentContainer.getId(), OrderFragment.TAG.hashCode()));
        if (fragment == null) {
            fragment = OrderFragment.newInstance();
        }
        return (OrderFragment) fragment;
    }

    private AccountFragment getNewsFragment() {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(
                makeFragmentName(fragmentContainer.getId(), AccountFragment.TAG.hashCode()));
        if (fragment == null) {
            fragment = AccountFragment.newInstance();
        }
        return (AccountFragment) fragment;
    }

    private MineFragment getMyFragment() {
        Fragment fragment = getSupportFragmentManager().findFragmentByTag(
                makeFragmentName(fragmentContainer.getId(), MineFragment.TAG.hashCode()));
        if (fragment == null) {
            fragment = MineFragment.newInstance();
        }
        return (MineFragment) fragment;
    }

    // FragmentPagerAdapter创建Tag的方法
    private static String makeFragmentName(int viewId, long id) {
        return "android:switcher:" + viewId + ":" + id;
    }

    private FragmentPagerAdapter mPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            if (position == 0) {
                return getMainFragment();
            } else if (position == 1) {
                return getAccountFragment();
            } else if (position == 2) {
                return getNewsFragment();
            } else if (position == 3) {
                return getMyFragment();
            }
            return getMainFragment();
        }

        @Override
        public long getItemId(int position) {
//            if (position == 0) {
//                return MainFragment.TAG.hashCode();
//            } else if (position == 1) {
//                return ProductFragment.TAG.hashCode();
//            } else if (position == 2) {
//                return NewsFragment.TAG.hashCode();
//            } else if (position == 3) {
//                return MyFragment.TAG.hashCode();
//            }
            return HomeFragment.TAG.hashCode();
        }

        @Override
        public int getCount() {
            return 4;
        }
    };

    //在需要的页面加上
    protected void setStatusBar() {
        //根据状态栏颜色来决定状态栏文字用黑色还是白色
//        StatusBarUtil.setStatusBarMode(this, false, R.color.blue);

    }

    //内部类，实现BroadcastReceiver
    public class LocationReceiver extends BroadcastReceiver {
        //必须要重载的方法，用来监听是
        // 否有广播发送
        @Override
        public void onReceive(Context context, Intent intent) {
            String intentAction = intent.getAction();
            if (intentAction.equals("location.reportsucc")) {
                Toast.makeText(MainActivity.this, intent.getStringExtra("key"), 1).show();
            }
        }
    }

    /**
     * APP更新接口
     */
    private void appUpdate() {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .appUpdate()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getCode() == 0) {
                        url = response.getData().getDownloadPath();
                        newVersion = response.getData().getVersionNumber();
                        mandatoryUpdate = response.getData().getMandatoryUpdate();
                        String nowVersion = getVersionName(MainActivity.this);
                        int isUpdate = compareVersion(newVersion, nowVersion);
                        if (isUpdate > 0) {
                            if (mandatoryUpdate.equals("1")) {
                                showMandatoryUpdaloadDialog(url);
                            } else {
                                showUpdaloadDialog(url);
                            }
                        }
                    } else {

                        showBindToast(response.getMsg());
                    }
                }, throwable -> {
                    throwable.printStackTrace();
                    hideProgressDialog();
                    if (CommonUtils.isNetworkAvailable(getContext()))
                        showBindToast("获取更新数据失败");
                    else
                        showBindToast("无网络连接，请稍后再试");
                }));
    }

    private void startUpload(String downloadUrl) {

        progressDialog = new ProgressDialog(this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMessage("正在下载新版本。。。");
        progressDialog.setCancelable(false);//不能手动取消下载进度对话框

        final String fileSavePath = getSaveFilePath(downloadUrl);
        HTTPCaller.getInstance().downloadFile(downloadUrl, fileSavePath, null, new ProgressUIListener() {

            //下载开始
            @Override
            public void onUIProgressStart(long totalBytes) {
                progressDialog.setMax((int) totalBytes);
                progressDialog.show();
            }

            //更新进度
            @Override
            public void onUIProgressChanged(long numBytes, long totalBytes, float percent, float speed) {
                progressDialog.setProgress((int) numBytes);
            }

            //下载完成
            @Override
            public void onUIProgressFinish() {
                Toast.makeText(MainActivity.this, "下载完成", Toast.LENGTH_LONG).show();
                progressDialog.dismiss();
                openAPK(fileSavePath);
            }

        });
    }

    public static String getSaveFilePath(String fileUrl) {
        String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1, fileUrl.length());//获取文件名称
        String newFilePath = Environment.getExternalStorageDirectory() + "/Download/" + fileName;
        return newFilePath;
    }

    private void openAPK(String fileSavePath) {

        File file = new File(fileSavePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
            // "cn.com.eyes3d.fileprovider"即是在清单文件中配置的authorities
            // 通过FileProvider创建一个content类型的Uri
            data = FileProvider.getUriForFile(this, "com.wisdom.benefit.jufa.fileProvider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
        } else {
//            data = Uri.fromFile(file);
            data = FileProvider.getUriForFile(this, "com.wisdom.benefit.jufa.fileProvider", file);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//安装完成后提示：完成 打开
        startActivity(intent);

    }

    /**
     * 获取当前版本号
     *
     * @param ctx
     * @return
     */
    public static String getVersionName(Context ctx) {
        // 获取packagemanager的实例
        String version = null;
        try {
            PackageManager packageManager = ctx.getPackageManager();
            //getPackageName()是你当前程序的包名
            PackageInfo packInfo = packageManager.getPackageInfo(ctx.getPackageName(), 0);
            version = packInfo.versionName;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }

    /**
     * 版本号对比
     *
     * @param s1
     * @param s2
     * @return
     */
    public static int compareVersion(String s1, String s2) {
        String[] s1Split = s1.split("\\.", -1);
        String[] s2Split = s2.split("\\.", -1);
        int len1 = s1Split.length;
        int len2 = s2Split.length;
        int lim = Math.min(len1, len2);
        int i = 0;
        while (i < lim) {
            int c1 = "".equals(s1Split[i]) ? 0 : Integer.parseInt(s1Split[i]);
            int c2 = "".equals(s2Split[i]) ? 0 : Integer.parseInt(s2Split[i]);
            if (c1 != c2) {
                return c1 - c2;
            }
            i++;
        }
        return len1 - len2;
    }

    /**
     * 提示更新弹框
     *
     * @param downloadUrl
     */
    private void showUpdaloadDialog(final String downloadUrl) {
        // 这里的属性可以一直设置，因为每次设置后返回的是一个builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 设置提示框的标题
        builder.setTitle("版本升级").
                setIcon(R.mipmap.ic_launcher). // 设置提示框的图标
                setMessage("发现新版本！请及时更新").// 设置要显示的信息
                setPositiveButton("确定", new DialogInterface.OnClickListener() {// 设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //判断是否有存储权限
                PackageManager pm = getPackageManager();
                boolean permission = (PackageManager.PERMISSION_GRANTED ==
                        pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", "com.wisdom.benefit.jufa"));
                if (permission) {
                    startUpload(downloadUrl);
                } else {
                    Toast.makeText(MainActivity.this, "请您开启存储权限", Toast.LENGTH_SHORT).show();
                }
            }
        }).setNegativeButton("取消", null);//设置取消按钮,null是什么都不做，并关闭对话框
        AlertDialog alertDialog = builder.create();
        // 显示对话框
        alertDialog.show();
    }

    /**
     * 提示强制更新弹框
     *
     * @param downloadUrl
     */
    private void showMandatoryUpdaloadDialog(final String downloadUrl) {
        // 这里的属性可以一直设置，因为每次设置后返回的是一个builder对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // 设置提示框的标题
        builder.setTitle("版本升级").
                setIcon(R.mipmap.ic_launcher). // 设置提示框的图标
                setMessage("发现新版本！请更新").// 设置要显示的信息
                setPositiveButton("确定", new DialogInterface.OnClickListener() {// 设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //判断是否有存储权限
                PackageManager pm = getPackageManager();
                boolean permission = (PackageManager.PERMISSION_GRANTED ==
                        pm.checkPermission("android.permission.WRITE_EXTERNAL_STORAGE", "com.wisdom.benefit.jufa"));
                if (permission) {
                    startUpload(downloadUrl);
                } else {
                    Toast.makeText(MainActivity.this, "请您开启存储权限", Toast.LENGTH_SHORT).show();
                }
            }
        });//设置取消按钮,null是什么都不做，并关闭对话框
        AlertDialog alertDialog = builder.create();
        // 显示对话框
        alertDialog.show();
        alertDialog.setCancelable(false);
    }
}

